/*
 * TaskManager.java
 *
 * Created on April 22, 2007, 9:08 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.xeerkat.agent;

import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;

/**
 *
 * @author alex
 */
public class TaskManager
{
   
   Map<UUID,Task> tasks;
   Map<UUID,Thread> threads;
   ThreadGroup group;
   Logger log;
         
   /** Creates a new instance of TaskManager */
   public TaskManager(Logger log)
   {
      this.log = log;
      tasks = new TreeMap<UUID,Task>();
      threads = new TreeMap<UUID,Thread>();
      group = new ThreadGroup("org.xeerkat.agent.threads");
   }
   
   public void run(Task task)
   {
      tasks.put(task.getId(),task);
      Thread t = new Thread(group,task);
      threads.put(task.getId(),t);
      t.start();
   }
   
   public Task remove(UUID id)
   {
      return tasks.remove(id);
   }
   
   public void list() {
      group.list();
   }
   
   public Task get(UUID id)
   {
      return tasks.get(id);
   }
   
   public Task create(final Runnable operation) {
      Task task = new SingleOperation(new AtomicBoolean(true)) {
         public void execute() {
            operation.run();
            remove(getId());
         }
      };
      return task;
   }
   
   public Task create(final Runnable operation,AtomicBoolean control) {
      Task task = new SingleOperation(control) {
         public void execute() {
            operation.run();
            remove(getId());
         }
      };
      return task;
   }
   
   public void stop() {
      for (Task task : tasks.values()) {
         log.info("Stopping "+task.getId());
         task.cancel();
         Thread t = threads.get(task.getId());
         t.interrupt();
      }
   }
   
}
